package com.huatai.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.util.ObjectUtil;
import com.huatai.user.entity.Department;
import com.huatai.user.entity.Post;
import com.huatai.user.entity.User;
import com.huatai.user.mapper.PostMapper;
import com.huatai.user.service.DepartmentService;
import com.huatai.user.service.PostService;
import com.huatai.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @program: ht-system
 * @description: 岗位管理接口
 * @author: songxiude
 * @create: 2023-02-20 10:45
 **/
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

	@Autowired
	private UserService userService;
	@Autowired
	private DepartmentService departmentService;
	/**
	 * 新增更新岗位信息
	 * @param post
	 * @return
	 */
	public boolean savePost(Post post) {
		if(Objects.isNull(post.getId()) || post.getId()<=0L){
			post.setId(IdWorker.getId());
		}
		return saveOrUpdate(post);
	}

	/**
	 * 删除岗位
	 * @param postId
	 * @return
	 */
	public boolean delPost(Long postId) {
		return removeById(postId);
	}

	/**
	 * 获取岗位列表
	 * @return
	 */
	public List<Post> getPostList() {
		List<Post> postList = baseMapper.selectList(Wrappers.<Post>lambdaQuery().eq(Post::getStatus, 0).orderByAsc(Post::getSort));
		return Optional.ofNullable(postList).orElse(Collections.emptyList());
	}

	@Override
	public List<User> listByDepartName(String departName) {
		Department department=departmentService.getOne(Wrappers.<Department>lambdaQuery().eq(Department::getDeptName,departName));
		if (ObjectUtil.isEmpty(department)){
			throw new RuntimeException("无法查询部门信息");
		}
		List<User> list = userService.list(Wrappers.<User>lambdaQuery().eq(User::getDeptId, department.getId()));
		list = list.stream().filter(x -> !x.getAccount().equals("admin")).collect(Collectors.toList());
		return list;
	}
}
